package com.roads.common.utils.file;

import org.apache.commons.lang3.StringUtils;

import java.io.File;

/**
 * 文件类型工具类
 *
 * @author nhp
 */
public class FileTypeUtils {

    private static final int NUMBER2 = 2;
    private static final int NUMBER3 = 3;
    private static final int NUMBER6 = 6;
    private static final int NUMBER7 = 7;
    private static final int NUMBER8 = 8;
    private static final int NUMBER9 = 9;
    private static final int NUMBER56 = 56;
    private static final int NUMBER66 = 66;
    private static final int NUMBER70 = 70;
    private static final int NUMBER71 = 71;
    private static final int NUMBER73 = 73;
    private static final int NUMBER74 = 74;
    private static final int NUMBER77 = 77;
    private static final int NUMBER78 = 78;
    private static final int NUMBER80 = 80;

    /**
     * 获取文件类型
     * <p>
     * 例如: master.txt, 返回: txt
     *
     * @param file 文件名
     * @return 后缀（不含".")
     */
    public static String getFileType(File file) {
        if (null == file) {
            return StringUtils.EMPTY;
        }
        return getFileType(file.getName());
    }

    /**
     * 获取文件类型
     * <p>
     * 例如: master.txt, 返回: txt
     *
     * @param fileName 文件名
     * @return 后缀（不含".")
     */
    public static String getFileType(String fileName) {
        int separatorIndex = fileName.lastIndexOf(".");
        if (separatorIndex < 0) {
            return "";
        }
        return fileName.substring(separatorIndex + 1).toLowerCase();
    }

    /**
     * 获取文件类型
     *
     * @param photoByte 文件字节码
     * @return 后缀（不含".")
     */
    public static String getFileExtendName(byte[] photoByte) {
        String strFileExtendName = "JPG";
        if ((photoByte[0] == NUMBER71) && (photoByte[1] == NUMBER73)
                && (photoByte[NUMBER2] == NUMBER70) && (photoByte[NUMBER3] == NUMBER56)
                && ((photoByte[4] == 55) || (photoByte[4] == 57)) && (photoByte[5] == 97)) {
            strFileExtendName = "GIF";
        } else if ((photoByte[NUMBER6] == NUMBER74) && (photoByte[NUMBER7] == NUMBER70) && (photoByte[NUMBER8] == NUMBER73) && (photoByte[NUMBER9] == NUMBER70)) {
            strFileExtendName = "JPG";
        } else if ((photoByte[0] == NUMBER66) && (photoByte[1] == NUMBER77)) {
            strFileExtendName = "BMP";
        } else if ((photoByte[1] == NUMBER80) && (photoByte[NUMBER2] == NUMBER78)
                && (photoByte[NUMBER3] == NUMBER71)) {
            strFileExtendName = "PNG";
        }
        return strFileExtendName;
    }
}